import net from "net";
import { Connector } from "./Connector";
import { ISocket, miscCfg } from "../util/defines";

/**
 * 客户端连接服务Tcp
 */
export class ConnectorTcp extends Connector {

    svr: net.Server;

    private _onSocket: (socket: ISocket) => void;

    start(port: number, onStart: () => void, onSocket: (socket: ISocket) => void, onError: (err: Error) => void): void {
        this._onSocket = onSocket;
        this.svr = net.createServer(this.onConnection.bind(this));
        this.svr.on("connection", this.onConnection.bind(this));
        this.svr.on("error", onError);
        this.svr.listen(port, onStart);
    }

    private onConnection(socket: net.Socket) {
        this._onSocket(new ConnectorTcpSocket(socket));
    }

}

class ConnectorTcpSocket implements ISocket {

    socket: net.Socket;
    remoteAddress: string;
    dataMaxLen: number = miscCfg.dataMaxLen;

    constructor(socket: net.Socket) {
        this.socket = socket;
        this.remoteAddress = socket.remoteAddress;
    }

    send(data: Buffer): void {
        this.socket.write(data);
    }

    on(event: "data", onData: (data: Buffer) => any): void;
    on(event: "close", onClose: () => any): void;
    on(event: "error", onError: (err: Error) => any): void;
    on(event: "data" | "close" | "error", listener: (...args: any[]) => any): void;
    on(event: any, listener: any): void {
        this.socket.on(event, listener);
    }

    off(event: "data" | "close" | "error", listener: (...args: any[]) => any): void {
        this.socket.off(event, listener);
    }

    close(): void {
        this.socket.end(() => {
            setTimeout(() => {
                this.socket.destroy();
            }, 1000);
        });
        this.socket.emit("close");
    }

}